package org.project.d.network.msg.serializer;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author lin
 * @version V1.0
 * @description
 * @date 2020/6/12 12:12 下午
 */
@Slf4j
public class ProtobufSerialization implements Serialization {


    @Override
    public byte[] serialized(Object object) {
        if (object==null){
            return new byte[]{};
        }
        if (object instanceof MessageLite){
            return ((MessageLite) object).toByteArray();
        }
        throw new RuntimeException("serialized object must is MessageLite but object is "+object.getClass());
    }

    @Override
    public <T> T deserialized(byte[] body, Class<T> tClass) {
        try {

            Constructor constructor = tClass.getDeclaredConstructor();
            constructor.setAccessible(true);
            Object o = constructor.newInstance();
            if (o instanceof MessageLite){
                MessageLite messageLite = (MessageLite) o;
                MessageLite defaultInstanceForType = messageLite.getDefaultInstanceForType();
                try {
                    return (T) defaultInstanceForType.getParserForType().parseFrom(body);
                } catch (InvalidProtocolBufferException e) {
                    log.error("proto deserialized err",e);
                }
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            log.error("create class err ",e);
        }
        return null;
    }

}
